<template>
    <el-button type="primary" plain @click="dialogFormVisible = true">
        新增
    </el-button>
    <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" label="编号" width="80" />
        <el-table-column prop="RoleName" label="角色名称" width="100">
            <template v-slot="scope">
                <el-link @click="LookUser(scope.row),GetRoleAccount(scope.row.Id)" underline="always">{{ scope.row.RoleName }}</el-link>
            </template>
        </el-table-column>
        <el-table-column prop="CreateName" label="创建人" width="110">
            <template v-slot="scope">
                <span v-if="!scope.row.CreateName">---</span>
                <span v-else>{{ scope.row.CreateName }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="CreateDate" label="创建日期" width="180">
            <template v-slot="scope">
                <span>{{ moment(scope.row.CreateDate).format("YYYY-MM-DD HH:mm:ss") }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="UpdateName" label="修改人" width="110">
            <template v-slot="scope">
                <span v-if="!scope.row.UpdateName">---</span>
                <span v-else>{{ scope.row.UpdateName }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="UpdateDate" label="修改日期" width="180">
            <template v-slot="scope">
                <span v-if="!scope.row.UpdateDate">---</span>
                <span v-else>{{ moment(scope.row.UpdateDate).format("YYYY-MM-DD HH:mm:ss") }}</span>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
            <template v-slot="scope">
                <el-button @click="DelRole(scope.row.Id)" type="primary" plain>删除</el-button>
                <el-button @click="UpdRole(scope.row)" type="success" plain>编辑</el-button>
                <el-button @click="RoleAccount(scope.row), GetRoleAccount(scope.row.Id)" type="Info"
                    plain>分配人员</el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-dialog v-model="dialogFormVisible" title="新增" width="800">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="角色名称" prop="RoleName">
                <el-input v-model="ruleForm.RoleName" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    确定
                </el-button>
                <el-button @click="dialogFormVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    <el-dialog v-model="UpddialogFormVisible" title="编辑" width="800">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="角色名称" prop="RoleName">
                <el-input v-model="ruleForm.RoleName" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="UpdsubmitForm(ruleFormRef)">
                    确定
                </el-button>
                <el-button @click="UpddialogFormVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    <el-dialog v-model="AccountdialogFormVisible" :title="`请设置【${Obj.RoleName}】角色的员工`" style="height: 300px;" width="800">
        <div class="common-layout">
            <el-container>
                <el-aside width="300px">
                    <el-tree style="max-width: 600px" :data="datas" node-key="value" @node-click="LD" />
                </el-aside>
                <el-aside width="300px">
                    <el-col :span="10">
                        <el-tree style="max-width: 600px" :data="datass" ref="treeRef" show-checkbox node-key="id"
                            v-model="user.AccountIds" />
                    </el-col>
                </el-aside>
            </el-container>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="AccountdialogFormVisible = false">
                    取消
                </el-button>
                <el-button type="primary" @click="Fenpei()">确定</el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog v-model="RoledialogFormVisible" :title="`属于角色【${Obj.RoleName}】的员工如下`" style="height: 300px;" width="800">
        <div class="flex gap-2">
            <el-tag v-for="tag in RoleUser" :key="tag" closable :disable-transitions="false"
                @close="handleClose(tag.AccountId)">
                {{ tag.Name }}
            </el-tag>
            <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" class="w-20" size="small"
                />
            <el-button v-else class="button-new-tag" size="small" @click="AccountdialogFormVisible = true,RoleAccount(Obj)">
                + 
            </el-button>
        </div>
    </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue';
import http from '@/http/axiosHelper';
import moment from 'moment';
import { type ElTree, type TreeInstance, type CheckboxValueType, ElMessage, ElMessageBox, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'
import { useCounterStore } from '@/stores/counter';
const store = useCounterStore()
const tableData = ref([])
onMounted(() => {
    ShowRole()
    ShowUser(-1)
})
const ShowRole = () => {
    http.get("/api/Role/GetRole").then(res => {
        tableData.value = res.data.Data
    })
}
//新增
const dialogFormVisible = ref(false)
const ruleForm = reactive({
    "LoginName": store.Account.Name,
    "CreateDate": "",
    "CreateName": "",
    "Id": 0,
    "RoleName": ""
})
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
    RoleName: [
        { required: true, message: '角色名称不能为空', trigger: 'blur' },
    ],
})
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            http.post("/api/Role/CreateRole", ruleForm).then(res => {
                if (res.data.Code == 200) {
                    ElMessage.success(res.data.Message)
                    ruleForm.RoleName = ""
                    ShowRole()
                    dialogFormVisible.value = false
                }
                else {
                    ElMessage.warning(res.data.Message)
                }
            })
            console.log('submit!')
        } else {
            console.log('error submit!', fields)
        }
    })
}
//修改
const UpddialogFormVisible = ref(false)
const UpdRole = (row: any) => {
    UpddialogFormVisible.value = true
    ruleForm.Id = row.Id
    ruleForm.RoleName = row.RoleName
    ruleForm.CreateDate = row.CreateDate
    ruleForm.CreateName = row.CreateName
}
const UpdsubmitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            http.post("/api/Role/UpdateRole", ruleForm).then(res => {
                if (res.data.Code == 200) {
                    ElMessage.success(res.data.Message)
                    ShowRole()
                    UpddialogFormVisible.value = false
                    ruleForm.RoleName = ""
                }
                else {
                    ElMessage.warning(res.data.Message)
                }
            })
            console.log('submit!')
        } else {
            console.log('error submit!', fields)
        }
    })
}
//删除
const DelRole = (id: any) => {
    ElMessageBox.confirm(
        '确认删除吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        http.get("/api/Role/DelRole", { params: { Id: id } }).then(res => {
            if (res.data.Code == 200) {
                ElMessage.success(res.data.Message)
                ShowRole()
            }
            else {
                ElMessage.warning(res.data.Message)
            }
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '取消删除',
        })
    })
}
//分配员工
const AccountdialogFormVisible = ref(false)

const RoleAccount = (row: any) => {
    AccountdialogFormVisible.value = true
    Obj.value.RoleName = row.RoleName
    user.value.RoleId = row.Id
    GetRoleAccount(user.value.RoleId)
}

const LD = (node: any, checked: boolean) => {
    if (checked) {
        const id = node.value
        ShowUser(id)
    }
    else {
        const id = 0
        ShowUser(id)
    }
}

const datas = ref([
    {
        label: '请选择部门',
        children: [
            {
                value: '1',
                label: 'IT信息部',
            },
            {
                value: '2',
                label: '人力资源部',
            },
            {
                value: '3',
                label: '财务部',
            },
            {
                value: '4',
                label: '销售部',
            },
        ],
    }
])

const datass = ref([])

const ShowUser = (id: any) => {
    http.get("/api/AccountRole/GetRoleUser", { params: { DepartmentId: id } }).then(res => {
        datass.value = res.data.Data
    })
}
const user = ref({
    AccountId: "",
    RoleId: "",
    AccountIds: []
})
const treeRef = ref<TreeInstance>()
const Fenpei = () => {
    var checkTree = treeRef.value?.getCheckedKeys(false)
    user.value.AccountId = checkTree?.toString()??''
    console.log(user.value);
    http.post("/api/AccountRole/CreateAccountRole", user.value).then(res => {
        if (res.data.Code == 200) {
            ElMessage.success(res.data.Message)
            ShowRole()
            GetRoleAccount(Obj.value.Id)
            AccountdialogFormVisible.value = false
        }
        else {
            ElMessage.warning(res.data.Message)
        }
    })
}
const GetRoleAccount = (id: any) => {
    http.get("/api/AccountRole/RoleUser", { params: { RoleId: id } }).then(res => {
        if (res.data.Data.length == 0) {
            treeRef.value?.setCheckedKeys([], true);
            return
        }
        res.data.Data.forEach((ss: any) => {
            user.value.AccountIds.push(ss.AccountId as never)
        })
        RoleUser.value = res.data.Data
        ShowUser(res.data.Data[0].Department)
        treeRef.value?.setCheckedKeys(user.value.AccountIds, false);
    })
}

const RoledialogFormVisible = ref(false)

const inputVisible = ref(false)
const inputValue = ref('')
const RoleUser=ref([{
    AccountId:"",
    Name:""
}])

const Obj = ref({
      "Id": "",
      "RoleName": "",
      "CreateName": "",
      "CreateDate": "",
      "UpdateName": "",
      "UpdateDate": ""
})
const LookUser = (row: any) => {
    console.log(row);
    RoledialogFormVisible.value = true
    Obj.value.RoleName = row.RoleName
    Obj.value.Id = row.Id
    GetRoleAccount(row.Id)
}


const handleClose = (tag: any) => {
    http.get("/api/AccountRole/DelRoleUser",{params:{AccountId:tag}}).then(res=>{
        if(res.data.Code==200){
            ElMessage.success(res.data.Message)
            GetRoleAccount(Obj.value.Id)
        }
        else{
            ElMessage.warning(res.data.Message)
        }
    })
}



</script>
<style>
.custom-header {
    .el-checkbox {
        display: flex;
        height: unset;
    }
}
</style>
<style scoped>
.el-link {
    margin-right: 8px;
}
</style>